//
//  JPTextView.m
//  Project
//
//  Created by apple on 15/5/31.
//  Copyright (c) 2015年 wangjinping. All rights reserved.
//

#import "JPTextView.h"

@implementation JPTextView

- (void) setTextContainerInset:(UIEdgeInsets)textContainerInset {
    [super setTextContainerInset:textContainerInset];
    if (_hintTv != nil) {
        [_hintTv setTextContainerInset:textContainerInset];
    }
}

- (void) setFont:(UIFont *)font {
    [super setFont:font];
    if (_hintTv != nil) {
        [_hintTv setFont:font];
    }
}

- (void)setText:(NSString *)text {
    [super setText:text];
    if (text.length>0) {
        [_hintTv setHidden:YES];
    }
}

#pragma mark
#pragma mark 设置placeholder
- (void) setPlaceHolder:(NSString *)hint textColor:(UIColor *)color {
    if (_hintTv == nil) {
        _hintTv = [[UITextView alloc] initWithFrame:self.bounds];
        [_hintTv setBackgroundColor:[UIColor clearColor]];
        [self addSubview:_hintTv];
    }
    [_hintTv setUserInteractionEnabled:false];
    [_hintTv setText:hint];
    [_hintTv setTextColor:color];
    [_hintTv setEditable:NO];
    [_hintTv setFont:self.font];
    [_hintTv setTextContainerInset:self.textContainerInset];
    if (!_isAddNotif) {
        _isAddNotif = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textBeginEdit:) name:UITextViewTextDidBeginEditingNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textEndEdit:) name:UITextViewTextDidEndEditingNotification object:nil];
    }
}

- (void)textBeginEdit:(NSNotification *) notif{
    if (_hintTv != nil) {
        [_hintTv setHidden:YES];
    }
}

- (void)textEndEdit:(NSNotification *) notif{
    if (_hintTv != nil) {
        if ([self text].length>0) {
            [_hintTv setHidden:YES];
        } else {
            [_hintTv setHidden:NO];
        }
    }
}
#pragma mark
#pragma mark 设置文字竖直居中
- (void) adjustTextVerticalCenter {
    _isAdd = YES;
    [self addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
}

#pragma mark - KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    UITextView *tv = object;
    // Center vertical alignment
    CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
    topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
    tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}


-(void)dealloc {
    if (_isAdd) {
        [self removeObserver:self forKeyPath:@"contentSize"];
    }
    if (_isAddNotif) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidEndEditingNotification object:nil];
    }
}

@end
